<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <!-- @keyup.enter.native="dataFormSubmitHandle()" -->
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="140px"
    >
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item prop="stationCode" label="站点代码">
            <el-input
              v-model="dataForm.stationCode"
              placeholder="请输入站点代码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item prop="stationName" label="站点名称">
            <el-input
              v-model="dataForm.stationName"
              placeholder="请输入站点名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item prop="address" label="位置">
            <el-input
              v-model="dataForm.address"
              placeholder="请输入位置"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item prop="province" label="省份">
            <el-select
              style="width:100%"
              v-model="dataForm.province"
              @change="slectCity"
              placeholder="请选择省份"
            >
              <el-option
                v-for="item in cityList"
                :key="item.dm"
                :label="item.mc"
                :value="item.dm"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item prop="city" label="城市">
            <el-select v-model="dataForm.city" style="width:100%" @change="selectArea" placeholder="请选择城市">
              <el-option
                v-for="item in cityChildren"
                :key="item.dm"
                :label="item.mc"
                :value="item.dm"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item prop="area" label="区域"> 
            <!-- areaChildren -->
            <!-- @change="selectArea" -->
            <el-select v-model="dataForm.area" style="width:100%"   placeholder="请选择区域">
              <el-option
                v-for="item in areaChildren"
                :key="item.dm"
                :label="item.mc"
                :value="item.dm"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item prop="contacts" label="联系人名称">
            <el-input
              v-model="dataForm.contacts"
              placeholder="请输入联系人名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item prop="contactsNumber" label="联系人电话">
            <el-input
              v-model="dataForm.contactsNumber"
              placeholder="请输入联系人电话"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item prop="type" label="类别">
            <!-- @change="selectArea" -->
            <el-select v-model="dataForm.type"  placeholder="请选择类别">
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
        <el-form-item  label="使用车系" class="role-list">
            <dealer-com :branName.sync="dataForm.branchChns" @getDataIput="getDataIput" :branchIds.sync="numberArray" placeholder="请选择" :query="true"></dealer-com>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item prop="status" label="站点线上状态" size="mini">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="0">{{ $t("user.status0") }}</el-radio>
              <el-radio :label="1">{{ $t("user.status1") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item prop="status" label="是否是服务供应商" size="mini">
            <el-radio-group v-model="dataForm.ifServiceProvider">
              <el-radio :label="0">{{ $t("user.status0") }}</el-radio>
              <el-radio :label="1">{{ $t("user.status1") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- contactsNumber -->
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from "lodash/debounce";
import dealerCom  from '@/components/comDealer/dealerCssom.vue'
import { isEmail, isMobile } from "@/utils/validate";
export default {
  components:{
    dealerCom
  },
  data() {
    return {
      visible: false,
      roleList: [],
      roleIdListDefault: [],
      typeList:[
        {
          name:"服务站",
          id:'0'
        },
        {
          name:"经销商",
          id:'1'
        },
        {
          name:"4S",
          id:'3'
        },
        {
          name:"备件经销商",
          id:'4'
        },
      ],
      cityList: [],//省份
      cityChildren:[],//市
      areaChildren:[],//区县
      numberArray:[],
      dataForm: {
        id: "",
        branchIds:[],
        stationCode: "",
        branchChns:"",
        contactsNumber: "",
        stationName: "",
        address: "",
        province: "",
        city: "",
        area: "",
        contacts: "",
        type: 0,
        ifServiceProvider:1,//1是 0否
        status: 1,
      },
    };
  },
  computed: {
    dataRule() {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        callback();
      };
      var validateConfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        if (this.dataForm.password !== value) {
          return callback(new Error(this.$t("user.validate.confirmPassword")));
        }
        callback();
      };
      var validateEmail = (rule, value, callback) => {
        if (value && !isEmail(value)) {
          return callback(
            new Error(
              this.$t("validate.format", { attr: this.$t("user.email") })
            )
          );
        }
        callback();
      };
      var validateMobile = (rule, value, callback) => {
        if (value && !isMobile(value)) {
          return callback(
            new Error(
              this.$t("validate.format", { attr: this.$t("user.mobile") })
            )
          );
        }
        callback();
      };
      return {
        stationCode: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        password: [{ validator: validatePassword, trigger: "blur" }],
        address: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        province: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        stationName:[
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        contacts:[
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        city:[
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        contactsNumber: [{ validator: validateMobile, trigger: "blur" }],
      };
    },
  },
  created() {
    
  },
  methods: {
    getDataIput(val){
      this.dataForm.branchChns = val.branchChns;
      this.dataForm.branchIds = val.branchIds;
    },
    oncancel(){
      this.visible = false
      this.$emit('canCle')
    },
    selectArea(val){
      this.getProvinceChlidren(val,2)
      this.dataForm.area = "";
    },
    slectCity(val) {
      // console.log(val,'111shen1111111')
      // this.cityList.forEach((item) => {
      //   if (item.dm == val) {
      //     this.cityChildren = item.children;
      //   }
      // });
      this.getProvinceChlidren(val,1)
      this.dataForm.city = "";
    },
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.getProvince();
        this.$refs["dataForm"].resetFields();
        this.roleIdListDefault = [];
      });
    },
    getProvince() {
      this.$http.get("/division/tree",).then((res) => {
        console.log(res.data.code == 0,'是么')
        if (res.data.code == 0) {
          this.cityList = res.data.data;
          if (this.dataForm.id) {
              this.getInfo();
            }
          // console.log(this.cityList,'this.cityList')
        }
      });
    },
   getProvinceChlidren(val,id){
      this.$http.get("/division/tree",{
        params:{
          sjjg:val,
        }
      }).then(res=>{
        if(res.data.code ==0 ){
          if(id == 1){
            this.cityChildren = res.data.data[0].children;
          }else{
            this.areaChildren = res.data.data[0].children;
          }
        }
      })
    },
         
// ssxq
    getInfo(){
      this.$http.get("/storemanage/" + this.dataForm.id, {}).then((res) => {
        if (res.data.code == 0) {
            // this.dataForm = {
            //   ...res.data.data
            // }
            Object.keys(this.dataForm).forEach(item=>{
                  
              this.dataForm[item] = res.data.data[item];
               if(item == 'province' || item == 'city' ||  item == 'area' || item =='type'){
                  this.dataForm[item] = String(res.data.data[item]);
              }
          })   
          // else if(item == 'city'){
          //       this.dataForm[item] = String(res.data.data[item]) || "" ;
          //     }else if(item == 'area'){
          //       this.dataForm[item] = String(res.data.data[item])  || "";
          //     }
       
          this.getProvinceChlidren(this.dataForm.province,1)
          this.getProvinceChlidren(this.dataForm.city,2)
          // this.dataForm.province = String(this.dataForm.province) || "";
          // this.dataForm.city = String(this.dataForm.city)  || "";
          // this.dataForm.area = String(this.dataForm.area)|| "";
          if(this.dataForm.branchChns.length>0){
            this.dataForm.branchChns = this.dataForm.branchChns.join(',')
          }
         if(this.dataForm.branchIds&&this.dataForm.branchIds.length>0){
            this.dataForm.branchIds.map(item=>{
              this.numberArray.push(Number(item))
            })
         }
        }
      });
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          let url
          if(!this.dataForm.id){
            url='storemanage/save'
          }else{
            url = 'storemanage/update'
          }
          // this.getProvinceChlidren(val,1)
          this.$http.post(url, {
            ...this.dataForm,
          })
            .then(({ data: res }) => {
         
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.oncancel()
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>

<style lang="scss">
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
